package com.lct.eq2.backup;

import com.lct.eq2.data.Attack;
import com.lct.eq2.data.Line;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MulticastServer {
    private ArrayList connectedServers;
    private boolean open;
    
    public static void main(String[] args) throws IOException {
        MulticastServer server = new MulticastServer();
    }
    
    public MulticastServer() {
        this.open = true;
        connectedServers = new ArrayList();
        try {
            // create socket
            ServerSocket server = new ServerSocket(13267, 5);
            while (open) {
                MulticastServerThread thread = new MulticastServerThread(server.accept(), this);
                thread.start();
                //System.out.println(System.currentTimeMillis() + " :: Accepted connection :");
            }
        } catch (IOException ex) {
            Logger.getLogger(MulticastServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void addServer(String server) {
        this.connectedServers.add(server);
    }
    
    public void removeServer(String server) {
        this.connectedServers.remove(server);
    }
    
    public void sendData(Object data) {
        MulticastClient client;
        String server = null;
        for (int x = 0; x < this.connectedServers.size(); x++) {
            server = this.connectedServers.get(x).toString();
            if (data instanceof Attack) {
                if (!((Attack)data).getOriginatingServer().equalsIgnoreCase(server)) {
                    //System.out.println("MulticastServer::sendData() - Sending data to " + server);
                    client = new MulticastClient(data, this.connectedServers.get(x).toString());
                    client.start();
                }
            } else if (data instanceof Line) {
                Line line = (Line)data;
//                if (!line.getOriginatingServer().equalsIgnoreCase(server)) {
//                    //System.out.println("Sending data to " + server + " from " + line.getOriginatingServer());
//                    client = new MulticastClient(data, server);
//                    client.start();
//                }
            }
        }
    }
    
}
